<!--  -->
<template>
  <div id="goods_supplier3 ">
    <div :class="!topbackground?'bg-linear-gradient':'bgImg'" :style="{'background-image': `url(${topbackground})`}">
      <van-search v-model="value" readonly @click="toSearch" shape="round" show-action placeholder="搜索店内商品" background="transparent">
        <template #action>
          <van-button v-if="showChangeAdrr" @click="addressShow = true" color="#ffffff" plain class="bg-transparent" type="info" size="small" hairline round>切换地址</van-button>
        </template>
      </van-search>
      <div class="padding-left-12 padding-right-12">
        <div class="padding-10 bg-fff border-radius-8 flex-a-c">
          <div class="margin-right-6 logo">
            <img :src="supplierInfo.supplier_info.logo" alt="" />
          </div>
          <div class="f-grow-1 t-l">
            <div class="f-15 f-bold">{{ supplierInfo.supplier_info.store_name }}</div>
            <div class="f-13 margin-top-4">{{ supplierInfo.supplier_info.full_address }}</div>
          </div>
        </div>
      </div>
    </div>

    <van-tabs v-model="active" ref="tabs" @change="onClickTab" color="var(--themeBaseColor)" sticky background="transparent" line-width="20px">
      <van-tab title="首页">
        <div class="padding-10 bg-fff border-radius-8 margin-10">
          <!-- 分类 -->
          <div class="gird-5" style="grid-row-gap: 12px;">
            <div class="gird-item" @click="toSearch(item.category_id)" v-for="(item, index) in supplierInfo.button_list" :key="index">
              <div class="logo">
                <img :src="item.icon_url" alt="" />
              </div>
              <p class="f-12 margin-top-2">{{ item.title }}</p>
            </div>
          </div>
        </div>
        <!-- 轮播图 -->
        <div class="margin-10">
          <van-swipe :loop="false" :width="300" indicator-color="white" :show-indicators="false">
            <van-swipe-item class="margin-right-6" v-for="(item, index) in supplierInfo.slide_list" :key="index">
              <img :src="item.image_url_url" class="border-radius-8" alt="" @click.stop="tolink(item.link)"/>
            </van-swipe-item>
            <van-swipe-item>
              <div style="width: 80px;"></div>
            </van-swipe-item>
          </van-swipe>
        </div>
        <!-- 分类商品列表 -->
        <div v-for="(item, index) in supplierInfo.category_subarea" :key="index">
          <div class="margin-left-10 margin-right-10 flex-j-sb">
            <div class="f-15 f-bold">{{ item.category_name }}</div>
            <div class="f-13 flex-a-c color-6E6E79" @click.stop="toSearch(item.id)">更多 <i class="iconfont icon-advertise-next"></i></div>
          </div>
          <div class="padding-10 bg-fff border-radius-8 margin-10" v-if="item.goods_list.length > 0">
            <div class="gird-3" style="grid-row-gap: 8px;grid-column-gap: 8px;">
              <div @click.stop="toGoods(child.id)"  v-for="(child, ind) in item.goods_list" :key="ind" class="flex-column overflow-hidden w-100">
                <div class="border-radius-8">
                  <img :src="child.thumb" alt="" />
                </div>
                <div style="flex: 1;"></div>
                <div class="f-12 t-l line-clamp-2 margin-top-4">{{ child.title }}</div>
                <div class="flex-j-sb" style="align-items: flex-end;">
                  <div class="flex-column t-l">
                    <div class="f-14 themeColor"><em class="f-12">￥</em>{{ child.min_price || child.price }}</div>
                    <div class="f-12 color-999999" v-if="Number(child.market_price) > 0 && Number(child.price) < Number(child.market_price)">￥{{ child.market_price }}</div>
                  </div>
                  <div class="bg-themeColor plus-icon" @click.stop="showGoodPup(child.id)">
                    <i class="iconfont icon-life-game-plus"></i>
                    <!-- 显示当前商品购物车已添加的数量 -->
                    <div class="cart-num-tag" v-if="goodsCartsTotal[child.id] && goodsCartsTotal[child.id].total">
                      {{ goodsCartsTotal[child.id].total }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="全部商品">
        <div class="gird-2 padding-10 " style="grid-row-gap: 10px;grid-column-gap: 10px;">
          <div @click.stop="toGoods(child.id)" v-for="(child, ind) in goodsArr" :key="ind" class="bg-fff flex-column overflow-hidden w-100 border-radius-8">
            <div class="">
              <img :src="child.thumb" alt="" />
            </div>
            <div style="flex: 1;"></div>
            <div class="flex-column padding-10">
              <div class="f-14 t-l line-clamp-2">{{ child.title }}</div>
              <div class="flex-j-sb" style="align-items: flex-end;">
                <div class="flex-column t-l">
                  <div class="f-15 themeColor"><em class="f-12">￥</em>{{ child.min_price || child.price }}</div>
                  <div class="f-12 color-999999" v-if="Number(child.market_price) > 0 && Number(child.price) < Number(child.market_price)">￥{{ child.market_price }}</div>
                </div>
                <div class="bg-themeColor plus-icon" @click.stop="showGoodPup(child.id)">
                  <i class="iconfont icon-life-game-plus"></i>
                  <!-- 显示当前商品购物车已添加的数量 -->
                  <div class="cart-num-tag" v-if="goodsCartsTotal[child.id] && goodsCartsTotal[child.id].total">
                    {{ goodsCartsTotal[child.id].total }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <div style="height: 150px;"></div>

    <!-- 底部购物车 -->
    <div class="bottom-car set-pc-styleLeft">
      <div class="car-box">
        <div class="car-num" @click.stop="showCarList = true">
          <div class="car-num-box">
            <i class="iconfont icon-all_buycar"></i>
            <div class="carnum-style">{{ cartsNum }}</div>
          </div>

          <div class="small-price">{{ $i18n.t("money") }}</div>
          {{ cartsTotal }}
        </div>
        <div class="car-add" @click.stop="checkGoods">结算</div>
      </div>
    </div>

    <!-- 购物车列表弹窗 -->
    <yz-cart-list :cardata="carList" class="carlist" v-model="showCarList" :showDestory="true" v-on:clearCart="clearCart" v-on:blur="blurCart" v-on:plus="addGoods" v-on:minus="reduceGoods">
      <!-- 底部购物车 -->
      <div class="bottom-car set-pc-styleLeft">
        <div class="car-box">
          <div class="car-num" @click.stop="showCarList = false">
            <div class="car-num-box">
              <i class="iconfont icon-all_buycar"></i>
              <div class="carnum-style">{{ cartsNum }}</div>
            </div>

            <div class="small-price">{{ $i18n.t("money") }}</div>
            {{ cartsTotal }}
          </div>
          <div class="car-add" @click.stop="checkGoods">结算</div>
        </div>
      </div>
    </yz-cart-list>

    <yz-specs v-model="popupSpecs" themeColor="var(--themeBaseColor)" :carts="carts" :goodsInfo="goodinfo" v-on:closeSpecsPopup="close_yz_specs_popup"></yz-specs>

    <yd-cityselect v-model="addressShow" :callback="addressCallback" :items="district"></yd-cityselect>

    <!-- 街道选择器 s -->
    <van-popup v-model="streetShow" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" closeable>
      <div class="pop-base-title">请选择街道</div>
      <div class="pop-base-content">
        <van-cell :border="false" center is-link v-for="(item, i) in districtVal" :key="i" @click.native="streetConfirm(item)" title-style="text-align:left">
          <span slot="title">{{ item.areaname }}</span>
        </van-cell>
      </div>
    </van-popup>
    <!-- 街道选择器 end -->

    <van-popup v-model="SupplierListPop" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" closeable>
      <div class="pop-base-title">选择供应商</div>
      <div class="pop-base-content">
        <van-list v-model="getSupplierDataloading" :finished="getSupplierDatafinished" finished-text="没有更多了" @load="getSupplierData">
          <div class="padding-10 bg-fff border-radius-8 flex-a-c margin-top-8" v-for="(item, ind) in SupplierList" :key="item.id">
            <div class="logo">
              <img :src="item.logo" alt="" />
            </div>
            <div class="f-grow-1 t-l padding-left-12 padding-right-12">
              <div class="f-15 f-bold">{{ item.store_name }}</div>
              <!-- <div class="f-13 margin-top-4">{{ item.area.name }}</div> -->
            </div>
            <van-button @click.stop="onSelectSup(item.id)" style="width: 60px;" color="var(--themeBaseColor)" type="info" size="small" round>进入</van-button>
          </div>
        </van-list>
      </div>
    </van-popup>
  </div>
</template>

<script>
import yzCartList from "components/ui_components/yz_cartList";
import yzSpecs from "components/ui_components/yz_specs";

export default {
  data() {
    return {
      topbackground: "",
      addressShow: false,
      district: district,
      form: {},
      //省市区id值
      districtVal: [],
      streetShow: false,
      isShowStreet: false,
      addressName: "",
      showChangeAdrr: false,
      point: {},
      SupplierListPop: false,
      SupplierList: [],
      getSupplierDataloading: false,
      getSupplierDataPage: 1,
      getSupplierDatafinished: false,

      imgPath: "",
      active: 0,
      supplierInfo: {
        supplier_info: {},
        slide_list: [],
        category_subarea: [],
        button_list: []
      },
      goodsArr: [],

      showCarList: false,
      cartsNum: 0,
      cartsTotal: 0,
      cart_ids: [],
      carList: [],
      goodsCartsTotal: [],
      popupSpecs: false,
      goodinfo: {}
    };
  },

  activated() {
    if (this.$route.params.id) {
      this.supplierid = this.$route.params.id;
      this.initPage();
    } else {
      this.showChangeAdrr = true;
      // 判断本地locals数据是否有一个供应商id RegionSuppliersID
      let RegionSuppliersID = localStorage.getItem("RegionSuppliersID");
      if (RegionSuppliersID) {
        this.supplierid = RegionSuppliersID;
        this.initPage();
      } else {
        this.addressShow = true;
      }
    }
  },

  components: { yzCartList, yzSpecs },

  computed: {},

  mounted() {},

  methods: {
    initPage() {
      this.getData();
      this.getCar();
    },

    async getData() {
      let { result, msg, data } = await $http.get("plugin.supplier-shop-three.frontend.index.index", { supplier_id: this.supplierid }, ".");
      if (result == 0) return this.$toast(msg);
      this.imgPath = this.$store.state.imgPath;
      let {supplier_info, slide_list, category_subarea,button_list,background} = data;
      this.supplierInfo.supplier_info = supplier_info;
      this.supplierInfo.slide_list = slide_list;
      this.supplierInfo.category_subarea = category_subarea;
      this.supplierInfo.button_list = button_list;
      this.topbackground = background;
    },
    onClickTab(index) {
      if (index == 1) {
        this.getGoodsData();
      }
    },
    async getGoodsData() {
      let { result, msg, data } = await $http.get("plugin.supplier-shop-three.frontend.index.all-goods", { supplier_id: this.supplierid }, ".");
      if (result == 0) return this.$toast(msg);
      this.goodsArr = data.data;
    },
    async getCar() {
      let { result, msg, data } = await $http.get("plugin.supplier-shop-three.frontend.member-cart.index", { supplier_id: this.supplierid }, ".");
      if (result == 0) return this.$toast(msg);
      //获取 data.list数组里merchant_id的值为this.supplierid的数据
      // let carList = data.list.filter(item => item.merchant_id == this.supplierid);
      // this.carList = carList[0].carts;
      this.carList = data.list;
      this.getFirstCart(this.carList);
    },
    // 计算购物车数量和总金额
    getFirstCart(data) {
      this.carts = data;
      this.cartsNum = 0;
      this.cartsTotal = 0;
      this.carts.forEach(item => {
        this.cartsNum += item.total;
        this.cartsTotal += item.total * item.goods_price;
      });
      this.goodsCartsTotal = this.calculateTotal(this.carts);
      this.cartsTotal = parseFloat(this.cartsTotal).toFixed(2);
    },
    //不同规格的同一商品求和
    calculateTotal(arr) {
      let temp = {};
      for (let i in arr) {
        if (arr.hasOwnProperty(i)) {
          let key = arr[i].goods_id;
          this.cart_ids.push(arr[i].id || arr[i].cart_id);
          if (temp[key]) {
            let good_id = temp[key].goods_id;
            temp[key].goods_id = good_id;
            temp[key].total = temp[key].total + arr[i].total;
          } else {
            temp[key] = {};
            temp[key].goods_id = arr[i].goods_id;
            temp[key].total = arr[i].total;
            temp[key].id = arr[i].id || arr[i].cart_id;
          }
        }
      }
      return temp;
    },

    async showGoodPup(_id) {
      if (this.activity_gid == _id) {
        this.popupSpecs = true;
        return;
      }
      this.activity_gid = _id;
      let { result, msg, data } = await $http.get("goods.goods.get-goods-page", { id: Number(_id) }, ".");
      if (result == 0) return this.$toast(msg);
      this.goodinfo = data.get_goods;
      this.$nextTick(() => {
        this.popupSpecs = true;
      });
    },
    close_yz_specs_popup(_optionsId, goodsCount, clicktype, id) {
      console.log("规格弹窗关闭了=====", _optionsId, goodsCount, clicktype, id);
      this.popupSpecs = false;
      if (clicktype == 1) {
        //点击确认按钮
        if (id) {
          // 有购物车记录
          this.updateCart(id, goodsCount);
        } else {
          // 新加入购物车
          this.addCart(this.activity_gid, goodsCount, _optionsId);
        }
      }
    },
    addGoods(e) {
      console.log("加一 ", e);
      this.updateCart(e.id, e.total + 1);
    },
    reduceGoods(e) {
      console.log("减一 ", e);
      this.updateCart(e.id, e.total - 1);
    },
    blurCart(e) {
      console.log("失去焦点了", e);
      this.updateCart(e.id, e.total);
    },
    async updateCart(id, num) {
      let json = { num: num, id: id, supplier_id: this.supplierid };
      let _url = "plugin.supplier-shop-three.frontend.member-cart.updateNumV2";
      if (num == 0) {
        _url = "plugin.supplier-shop-three.frontend.member-cart.destroy";
        json = { ids: id, supplier_id: this.supplierid };
      }

      let { result, msg, data } = await $http.get(_url, json, ".");
      if (result == 0) return this.$toast(msg);
      this.getCar();
    },
    async addCart(gid, total, option_id) {
      let { result, msg, data } = await $http.get(
        "plugin.supplier-shop-three.frontend.member-cart.store",
        {
          goods_id: gid,
          total: total,
          option_id: option_id,
          supplier_id: this.supplierid
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.getCar();
    },
    checkGoods() {
      if (this.cartsNum == 0) {
        return this.$toast("购物车为空");
      }
      this.$router.push(
        this.fun.getUrl(
          "goodsorder",
          {},
          {
            tag: "suppThreeCart",
            cart_ids: this.cart_ids.join(",")
          }
        )
      );
    },
    clearCart(e) {
      if(e == 'all') {
        this.$dialog.confirm({
          title: "提示",
          message: "确定清空购物车吗?"
        }).then(() => {
          this.clearCartAction();
        });
      }
    },
    async clearCartAction() {
      $http.get("plugin.supplier-shop-three.frontend.member-cart.allDestroy", { supplier_id: this.supplierid }, ".").then(response => {
        if (response.result == 1) {
          this.getCar();
        } else {
          this.$toast(response.msg);
        }
      });
    },

    // 跳转分类
    toSearch(id = "") {
      if(!id) {
        this.$refs.tabs.scrollTo(1);
        return;
      }
      this.$router.push(this.fun.getUrl("SupplierSearch", { sid: this.supplierid, cid: id }));
    },
    tolink(link) {
      if (link) {
        window.location.href = link;
      }
    },
    toGoods(id){
      this.$router.push(this.fun.getUrl("goods", { id: id }));
    },

    //地址回调
    addressCallback(obj) {
      this.form.streetName = "";
      this.districtVal = "";
      this.form.province = obj.itemName1;
      this.form.city = obj.itemName2;
      this.form.district = obj.itemName3;

      this.province_id = obj.itemValue1;
      this.city_id = obj.itemValue2;
      this.district_id = obj.itemValue3;

      this.addressName = obj.itemName1 + " " + obj.itemName2 + " " + obj.itemName3;
      this.getStreet(obj.itemValue3);
    },
    //街道选择
    streetConfirm(item) {
      this.form.streetName = item.areaname;
      this.street_id = item.id;
      this.streetShow = false;
      this.getSupplierDataPage = 1;
      this.getSupplierDatafinished = false;
      this.SupplierList = [];
      this.SupplierListPop = true;
      // this.onSelectStreet();
      // this.getSupplierData();
    },
    //获取街道数据
    getStreet(param) {
      this.district_id = param;
      $http
        .get("member.memberAddress.street", { district_id: this.district_id }, ".")
        .then(response => {
          if (response.result == 1) {
            if (!this.fun.isTextEmpty(response.data) && response.data.length > 0) {
              this.districtVal = response.data;
              this.streetShow = true;
            }
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // onSelectStreet() {
    //   console.log("onSelectStreet",this.district_id,this.addressName + this.form.streetName);
    //   //将选择的街道id转为对应的经纬度，利用高德地图的接口
    //   this.geocoder = new AMap.Geocoder({
    //     city: this.district_id //城市设为北京，默认：“全国”
    //   });
    //   this.geocoder.getLocation(this.addressName + this.form.streetName, (status, result) => {
    //     console.log(status, result);
    //     if (status === "complete" && result.geocodes.length) {
    //       let lnglat = result.geocodes[0].location;
    //       this.point = this.fun.bd_encrypt(lnglat.lng, lnglat.lat);
    //       this.getSupplierData();
    //     }
    //   });
    // },
    async getSupplierData() {
      this.getSupplierDataloading = true;
      let { result, msg, data } = await $http.get(
        "plugin.supplier-shop-three.frontend.preposition.get-district-supplier-list",
        {
          page: this.getSupplierDataPage || 1,
          province_id: this.province_id,
          city_id: this.city_id,
          district_id: this.district_id,
          street_id: this.street_id || 0
        },
        "."
      );
      this.getSupplierDataloading = false;
      if (result == 0) return this.$toast(msg);
      this.getSupplierDataPage += 1;
      if (data.current_page == data.last_page) {
        this.getSupplierDatafinished = true;// 数据全部加载完成
      }
      this.SupplierList = this.SupplierList.concat(data.data);
      if(this.SupplierList.length == 0) {
        this.$dialog.alert({
          message: '该街道暂无供应商，请重新选择',
        }).then(() => {
          this.SupplierListPop = false;
          this.addressShow = true;
        });
      }
      // this.SupplierListPop = true;
    },
    onSelectSup(id) {
      this.SupplierListPop = false;
      this.supplierid = id;
      this.initPage();
      localStorage.setItem("RegionSuppliersID", id);
    }
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .van-tabs__line {
  bottom: 22px !important;
}
::v-deep .van-sticky--fixed {
  background: #fff !important;
}
.pop-base-class {
  .pop-base-title {
    margin: 18px 12px 12px;
    font-size: 1rem;
    font-weight: bold;
    text-align: left;
  }
  .pop-base-content {
    min-height: 45vh;
    max-height: 55vh;
    overflow: scroll;
    padding: 0 0.75rem 5rem;
  }
  .pop-base-bottom {
    padding: 0.625rem 0.875rem;
    background: #ffffff;
  }
}
.bg-linear-gradient {
  background-image: -webkit-gradient(linear, left top, left bottom, from(var(--themeBaseColor)), to(#f5f5f5));
  background-image: -webkit-linear-gradient(var(--themeBaseColor), #f5f5f5);
  background-image: linear-gradient(var(--themeBaseColor), #f5f5f5);
}
.bgImg {
  background-size: cover;
  background-position: center;
}
.padding-12 {
  padding: 0.75rem;
}
.bg-transparent {
  background-color: transparent;
}
.logo {
  width: 56px;
  height: 56px;
  border-radius: 29px 29px 29px 29px;
  overflow: hidden;
}
img {
  width: 100%;
  height: 100%;
  display: block;
  margin: 0;
}
.overflow-hidden {
  overflow: hidden;
}
.w-100 {
  width: 100%;
}
.plus-icon {
  width: 20px;
  height: 20px;
  line-height: 20px;
  border-radius: 50%;
  color: #fff;
  position: relative;
  margin-right: 4px;
}
.cart-num-tag {
  position: absolute;
  top: -10px;
  right: -4px;
  line-height: 14px;
  background: #fca624;
  border: 1px solid #fff;
  color: #fff;
  border-radius: 50%;
  padding: 0 4px;
  font-size: 10px;
}
// ----------------
.bottom-car {
  position: fixed;
  width: 100%;
  height: 4.5rem;
  left: 0;
  bottom: -1px;
  display: flex;
  align-items: center;
  background-image: linear-gradient(180deg, hsla(0, 0%, 100%, 0), #fff 19%);

  .car-box {
    border: 1px solid var(--themeBaseColor);
    border-radius: 1.5rem;
    display: flex;
    align-items: center;
    height: 3rem;
    line-height: 3rem;
    width: 90%;
    margin: 0 auto;
    overflow: hidden;

    .car-num-box {
      position: relative;
      width: 3rem;
      text-align: center;

      .carnum-style {
        position: absolute;
        height: 1rem;
        right: 0;
        top: 5px;
        line-height: 1rem;
        background: var(--themeBaseColor);
        border-radius: 1rem;
        color: #fff;
        padding: 0 0.25rem;
        font-size: 0.75rem;
      }
    }

    .car-num {
      width: 50%;
      text-align: left;
      color: var(--themeBaseColor);
      display: flex;

      i {
        font-size: 1.5rem;
      }

      .small-price {
        font-size: 0.75rem;
      }

      font-size: 1.125rem;
    }

    .car-add {
      flex: 1;
      text-align: center;
      background-color: var(--themeBaseColor);
      color: #fff;
    }
  }
}

.carlist {
  .bottom-car {
    position: relative;
  }
}
</style>
